#pragma once
#include <QVector>
#include <QPointF>
#include <QLineF>

/* 三次贝塞尔曲线采样 */
static QVector<QPointF> sampleCubicBezier(const QPointF &p0,
                                          const QPointF &p1,
                                          const QPointF &p2,
                                          const QPointF &p3,
                                          int steps = 32)
{
    QVector<QPointF> pts;
    for (int i = 0; i <= steps; ++i) {
        qreal t = qreal(i) / steps;
        qreal t1 = 1.0 - t;
        QPointF p = t1*t1*t1*p0 + 3*t1*t1*t*p1 + 3*t1*t*t*p2 + t*t*t*p3;
        pts << p;
    }
    return pts;
}

/* 点到线段投影距离 */
static qreal pointToSegmentDistance(const QPointF &p,
                                    const QPointF &a,
                                    const QPointF &b)
{
    QPointF ab = b - a;
    qreal len2 = ab.x()*ab.x() + ab.y()*ab.y();
    if (len2 < 1e-6) return QLineF(p, a).length();
    qreal t = qBound(0.0, QPointF::dotProduct(p - a, ab) / len2, 1.0);
    QPointF proj = a + t * ab;
    return QLineF(p, proj).length();
}

/* 检查是否需要在 a-b 之间插入新节点 */
static bool shouldInsertBezier(const QPointF &prev,
                               const QPointF &curr,
                               const QPointF &next,
                               qreal maxDist = 60.0,      // 1. 曲线距离阈值
                               qreal minSegLen = 80.0)    // 2. 段内最小像素间距
{
    /* 闸门 1：如果 prev 与 next 已很近，不再插点 */
    if (QLineF(prev, next).length() < minSegLen)
        return false;

    /* 闸门 2：贝塞尔曲线距离检测 */
    QPointF midCtrl = (prev + next) * 0.5;          // 用中点做简化贝塞尔
    qreal dist = pointToSegmentDistance(curr, prev, next);
    return dist > maxDist;
//    /* 用三次贝塞尔：控制点取两端中点，模拟“原直线” */
//    QPointF c1 = (oldA + oldB) * 0.5;
//    QPointF c2 = (newA + newB) * 0.5;
//    auto curve = sampleCubicBezier(oldA, c1, c2, newB, 16);
//    for (const QPointF &pt : curve) {
//        if (pointToSegmentDistance(pt, newA, newB) > maxDist)
//            return true;
//    }
//    return false;
}
